import axios from "axios";
export interface BaiYunUser {
    balance: string;
    phone: string;
    id: string;
    status: number;
}
export class BaiYunCore {
    username: string;
    password: string;
    constructor(account: string, pwd: string) {
        this.username = account;
        this.password = pwd;
    }
    /**
     * 
    //1.查询用户信息
    请求接口：http://202.189.5.105:7899/api/user?account=用户账号&pwd=用户密码
    请求参数：
        account: 用户账号
        pwd: 用户密码
    请求方法： GET && POST
    请求结果实例：
        {
        "flag": true,
        "code": 20000,
        "message": "请求成功",
        "data": {
            "balance": "814.60",  //余额
            "phone": "xxxx",  //账号
            "id": "xxxxx", //用户id
            "status": 0
        },
        "orderId": null
    }
     */
    private host: string = `http://202.189.5.105:7899`
    async apiUser(): Promise<BaiYunUser> {
        const url = `${this.host}/api/user?account=${this.username}&pwd=${this.password}`
        const data = await axios.get(url).then(res => res.data)
        if (data.code === 20000) {
            return data.data;
        }
        throw new Error(data.message)
    }


    /**
     * //2.查询授权记录
请求接口：http://202.189.5.105:7899/api/record?account=用户账号&pwd=用户密码&pageNumber=1&pageSize=20&appId=xxx
请求参数：
    account: 用户账号
    pwd: 用户密码
    pageNumber: 页码
    pageSize: 每页返回的数据
    appId: 查询指定appId的授权记录，可不传，不传返回所有的
请求方法： GET && POST
请求结果实例：
{
    "flag": true,
    "code": 20000,
    "message": "请求成功",
    "data": {
        "currentTime": 1681739218302,
        "list": [
            {
                "id": "164792907467020000",
                "taskId": "168173188300000",
                "nickname": "快手极速版",
                "appId": "wx42d6d3bdc1cb2bdc",
                "price": 0.75,
                "imageUrl": "http://mmbiz.qpic.cn/mmbiz_png/fibzicDfgmF3BvWs8mcgwn3wh9L74XRNAj2ZJf1oicIymicGGP2qeRicaCqBYYbzpSGYSl1WrSJaegH367QibxlY5GAw/0?wx_fmt=png",
                "createTime": "2023-04-17 19:44:43",
                "authUrl": ""
            },
            {
                "id": "164792907467020000",
                "taskId": "168173188300000",
                "nickname": "拼多多",
                "appId": "wx77d53b84434b9d9a",
                "price": 1.00,
                "imageUrl": "http://mmbiz.qpic.cn/mmbiz_png/tUibHyN65J4HgaqSYfmDUFOOg5qmibEGib2PbJ89g4x7QUOZZlLichg1pFPP1ib1AREic5aSEOelUpeVuxooWDbTGElg/0?wx_fmt=png",
                "createTime": "2023-04-14 19:02:58",
                "authUrl": "https://open.weixin.qq.com/connect/confirm?uuid=081DEHOZ1cGYll2w"
            }
        ]
    },
    "orderId": null
}
     */

    async apiRecord(appid: string, page: number = 1, psize: number = 20) {
        const url = `${this.host}/api/record?account=${this.username}&pwd=${this.password}&pageNumber=${page}&pageSize=${psize}&appId=${appid}`
        const data = await axios.get(url).then(res => res.data)
        if (data.code === 20000) {
            return data.data;
        }
        throw new Error(data.message)
    }


    /**
     * 
//3.授权 && 复扫
请求接口：http://202.189.5.105:7899/api/auth?account=xxx&pwd=xxxxx&appId=wx32540bd863b27570&id=&channel=1&authType=1&url=
请求参数：
    account: 用户账号
    pwd: 用户密码
    appId: 需要授权app或小程序所对应的appId
    platformId: 项目ID （项目ID和appId两个传其中一个即可授权，联合授权时需要两个都传递）
    id: 订单ID，复扫时需要传入
    channel: 授权通道  1 2 3 分别对应不同的通道，例如 1.对应新号 2.对应老号
    authType: 授权方式  1.code 授权（app和小程序） 2.扫码授权 （app或网页），扫码授权方式必须传入授权链接
    url: 需要授权的链接，扫码授权时必须传入 （扫码授权需要进行URL编码不可直接请求授权链接）   
请求方法： GET && POST
请求结果实例：
1.小程序code返回：
    {"Flag":true,"code":20000,"message":"请求成功","data":{"code":"0c3l9l000ZOywQ1lRz200Yabkc2l9l0d","orderId":"1691818723109507072","taskId":"1692195990653287"}}

2.APPcode返回：
    {"Flag":true,"code":20000,"message":"请求成功","data":{"code":"wx5dfbe0a95623607b://oauth?code=033MZd0005alCR1z21200ihijm4MZd0G\u0026state=","orderId":"1759906139069222912","taskId":"1708429295686239"}}

3.小程序code＋userdata+phonedata返回：
    {"Flag":true,"code":20000,"message":"请求成功","data":{"code":"{\"userData\":\"\",\"phoneData\":\"{\\\"wx_phone\\\":{\\\"mobile\\\":\\\"18041994784\\\",\\\"show_mobile\\\":\\\"180****4784\\\",\\\"need_auth\\\":true,\\\"allow_send_sms\\\":true},\\\"custom_phone_list\\\":[{\\\"mobile\\\":\\\"17114782882\\\",\\\"show_mobile\\\":\\\"171****2882\\\",\\\"need_auth\\\":false,\\\"allow_send_sms\\\":true,\\\"encryptedData\\\":\\\"ZI/KaYxvr2I+V0GFxT4Xb/BulviCTSCZN8UGSGIAap9izqcpa7/qwK7+rH+/IVEVQWs05QAbd0Cx8z7g/Gnl2CFVcyeTILPU/OoavGL77wqnPnG1bJLjyzpAA718eGcycZd4lxx/G/fzUNcHW8bvTi/bqxd7hnlJgcaXYvDq+yYMBm47yLVBHIfUJYQzhZrYaCHeWi/W6zSvv2lzRbxZbw==\\\",\\\"iv\\\":\\\"VoAVcI6i9n3CuTf8wfWiBg==\\\",\\\"cloud_id\\\":\\\"71_MpC9HyRr9Kea7gaYWgcLB_e1TzCnafsbgxgBY7Vht6_H0OQNg-CYHIA4m2o\\\",\\\"data\\\":\\\"{\\\\\\\"code\\\\\\\":\\\\\\\"a73c10925b90683750905aa0e3c944c55ff86c3018145b55affc4dd21678af6c\\\\\\\"}\\\"}]}\",\"code\":\"0f3Cnl000XfuwQ1nEb000Ft82z2Cnl0z\"}","orderId":"1691819674210144256","taskId":"1692196217385680"}}

     */

    async apiAuth(appid: string, channel: number = 1, authType: number = 1) {
        const url = `${this.host}/api/auth?account=${this.username}&pwd=${this.password}&appId=${appid}&id=&channel=${channel}&authType=${authType}&url=`
        const data = await axios.get(url).then(res => res.data)
        if (data.code === 20000) {
            return data.data;
        }
        throw new Error(data.message)
    }

    async auto(appid: string, channel: number = 1, authType: number = 1) {
        try {
            return await this.apiAuth(appid, channel, authType)
        } catch (e) {
            await new Promise<void>((resolve, reject) => {
                setTimeout(() => resolve(), 1000)
            })
            return await this.auto(appid, channel, authType)
        }
    }
}